package model

import (
	log "github.com/sirupsen/logrus"
	edge_security_client "qabx.net/safe-app-center/pkg/client/edge_security"
	"qabx.net/safe-app-center/pkg/utils"
	"strings"
)

type TblDevice struct {
	DeviceId   int    `json:"device_id"`
	DeviceMac  string `json:"device_mac"`
	DeviceIp   string `json:"device_ip"`
	DeviceIpv6 string `json:"device_ipv6"`
	DeviceName string `json:"device_name"`
	IsDel      int    `json:"is_del"`
	CreateTime string `json:"create_time"`
	UpdateTime string `json:"update_time"`
}

func (s *TblDevice) GetDeviceByMac() (*TblDevice, error) {
	res := &TblDevice{}
	dbClient, _ := utils.GetDbClient()

	_, err := dbClient.Client.Where("is_del =0 and device_mac = ?", strings.ToUpper(s.DeviceMac)).Limit(1).Get(res)
	return res, err
}

func (s *TblDevice) GetDeviceAndAddDevice(pppoeName string, gatewayId int, areaNo string) (*TblDevice, error) {
	device, err := s.GetDeviceByMac()
	if err != nil {
		return nil, err
	}
	if device == nil || device.DeviceId == 0 {
		err = addOrUpdateDeviceList(pppoeName, gatewayId, areaNo)
		if err != nil {
			return nil, err
		}
		device, err = s.GetDeviceByMac()
		if err != nil {
			return nil, err
		}
	}
	return device, nil
}

func addOrUpdateDeviceList(pppoeName string, gatewayId int, areaNo string) error {
	tblGateway := &TblGateway{PppoeName: pppoeName, GatewayId: gatewayId}
	//更新当前设备信息
	terminalList, err := edge_security_client.CallGetTerminalList(pppoeName, uint32(utils.GetRandomId()), areaNo)
	if err != nil {
		log.Errorf("client error:CallGetTerminalList:%s", err.Error())
		return err
	}

	//1.获取本地库设备信息
	gatewayDeviceList, err := GetGatewayDeviceList(gatewayId)
	if err != nil {
		log.Errorf("db error: GetGatewayDeviceRelList:%s", err.Error())
		return err
	}

	tm := terminalList.Tm

	if len(tm) == 0 && len(gatewayDeviceList) == 0 {
		return nil
	}
	if len(tm) > 0 && len(gatewayDeviceList) == 0 {
		deviceList := make([]*TblDevice, 0)
		for _, v := range tm {
			deviceInfo := &TblDevice{}
			deviceInfo.DeviceIp = v.Ip
			deviceInfo.DeviceIpv6 = v.Ipv6
			deviceInfo.DeviceName = v.Name
			deviceInfo.DeviceMac = v.Mac
			deviceList = append(deviceList, deviceInfo)
		}
		// 添加本地库设备信息
		err = tblGateway.AddGatewayDevice(deviceList)
		if err != nil {
			log.Errorf("db error: AddGatewayDevice:%s", err.Error())
			return err
		}
		return nil
	}

	onLineDeviceIds := []int{}
	deviceMap := make(map[string]*GatewayDevice)
	for _, v := range gatewayDeviceList {
		v.DeviceMac = strings.ToUpper(v.DeviceMac)
		deviceMap[v.DeviceMac] = v
		if v.IsOnline == 1 {
			onLineDeviceIds = append(onLineDeviceIds, v.DeviceId)
		}
	}

	if len(tm) == 0 && len(gatewayDeviceList) > 0 {
		// 网关下所有在线设备下线
		if len(onLineDeviceIds) > 0 {
			err = tblGateway.UpdateGatewayDeviceIsOnline(0, onLineDeviceIds)
			if err != nil {
				log.Errorf("db error: UpdateGatewayDeviceIsOnline:%s", err.Error())
				return err
			}
		}
		return nil
	}

	if len(tm) > 0 && len(gatewayDeviceList) > 0 {
		addDeviceList := make([]*TblDevice, 0)
		updateDeviceList := make([]*TblDevice, 0)
		for _, v := range tm {
			v.Mac = strings.ToUpper(v.Mac)
			if deviceMap[v.Mac] != nil {
				//更新设备列表
				deviceInfo := &TblDevice{}
				deviceInfo.DeviceIp = v.Ip
				deviceInfo.DeviceIpv6 = v.Ipv6
				deviceInfo.DeviceName = v.Name
				updateDeviceList = append(updateDeviceList, deviceInfo)
			} else {
				//添加设备列表
				deviceInfo := &TblDevice{}
				deviceInfo.DeviceIp = v.Ip
				deviceInfo.DeviceIpv6 = v.Ipv6
				deviceInfo.DeviceName = v.Name
				deviceInfo.DeviceMac = v.Mac
				addDeviceList = append(addDeviceList, deviceInfo)
			}

		}
		//添加设备
		if len(addDeviceList) > 0 {
			err = tblGateway.AddGatewayDevice(addDeviceList)
			if err != nil {
				log.Errorf("db error: AddGatewayDevice:%s", err.Error())
				return err
			}
		}
		// 更新设备
		if len(updateDeviceList) > 0 {
			err = tblGateway.UpdateGatewayDevice(updateDeviceList)
			if err != nil {
				log.Errorf("db error: UpdateGatewayDevice:%s", err.Error())
				return err
			}
		}
		return nil
	}
	return nil
}
